package orm

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"myapp/web/green/models"
)

//仓库物品
type Goods struct {
	Id            int64   `orm:"column(_id);pk;auto"`                      //物品ID
	Number        string  `orm:"column(_number)"`                          //物品编号
	Name          string  `orm:"column(_name)"`                            //名称
	Specification string  `orm:"column(_specification)"`                   //规格
	Quantity      float64 `orm:"column(_quantity);digits(25);decimals(5)"` //数量
	QuantityUnit  string  `orm:"column(_quantityunit)"`                    //数量单位
	Price         float64 `orm:"column(_price);digits(25);decimals(5)"`    //参考价格
	PriceUnit     string  `orm:"column(_priceunit)"`                       //价格单位

	//Companyname string `orm:"column(_companyname)"` //供应商名称
	Warehouseid int `orm:"column(_warehouseid)"` //仓库ID

	//Company   *Company   `orm:"-"` //供应商
	//Warehouse *Warehouse `orm:"-"` //所在仓库
}

//列表
func (this *Goods) List(o orm.Ormer) ([]orm.Params, error) {
	var list []orm.Params
	_, err := o.QueryTable("_goods").Values(&list)
	if err != nil {
		return nil, err
	}
	return list, nil
}

//创建
func (this *Goods) Create(o orm.Ormer) (int64, error) {
	id, err := o.Insert(this)
	if err != nil {
		return -1, err
	}
	return id, nil
}

//查询记录是否存在，不存在就创建
func (this *Goods) ReadOrCreate(o orm.Ormer, str string) (bool, int64, error) {
	created, id, err := o.ReadOrCreate(this, str)
	return created, id, err
}

//查询单条记录
func (this *Goods) Read(o orm.Ormer, fields ...string) (models.Reader, error) {
	err := o.Read(this, fields...)
	if err != nil {
		return nil, err
	}
	return this, nil
}

//通过数据库主键字段更新，可指定更新字段，参数为struct字段的字符串
func (this *Goods) Update(o orm.Ormer, fields ...string) error {
	_, err := o.Update(this, fields...)
	if err != nil {
		return err
	}
	return nil
}

//更新多条记录
func (this *Goods) MultiUpdate(o orm.Ormer, params orm.Params, args ...interface{}) error {
	fmt.Println("params: ", params)
	_, err := o.QueryTable("_goods").Filter("_id__in", args).Update(params)
	//_, err = o.Update(this, fields...)
	if err != nil {
		return err
	}
	return nil
}

//通过数据库主键字段删除
func (this *Goods) Delete(o orm.Ormer) error {
	_, err := o.Delete(this)
	if err != nil {
		return err
	}
	return nil
}

//删除多条记录
func (this *Goods) MultiDelete(o orm.Ormer, args ...interface{}) error {
	_, err := o.QueryTable("_goods").Filter("_id__in", args).Delete()
	if err != nil {
		return err
	}
	return nil
}
